/**
 * 演示程序当前的 “注册/登录” 等操作，是基于 “本地存储” 完成的
 * 当您要参考这个演示程序进行相关 app 的开发时，
 * 请注意将相关方法调整成 “基于服务端Service” 的实现。
 **/
(function($, owner) {
	$.plusReady(function() {
		owner.deviceId = '';
		owner.setDeviceId = function() {
			owner.deviceId = plus.device.uuid;
			owner.msgType = '';
			owner.sendMsgMobile = '';
			owner.sendMsgUrl = '';
		};
		/**
		 * 用户登录
		 **/
		owner.login = function(loginInfo, callback) {
			var e=window.event || arguments[0];
			e.preventDefault();
			owner.setDeviceId();
			callback = callback || $.noop;
			loginInfo = loginInfo || {};
			loginInfo.userName = loginInfo.userName || '';
			loginInfo.password = loginInfo.password || '';
			loginInfo.deviceId = owner.deviceId;

			if(!loginInfo.userName) {
				document.getElementById("message").innerHTML = '请填写用户名！';
				document.getElementById("message").className = "transition";
				return false;
			} else if(!loginInfo.password) {
				document.getElementById("message").innerHTML = '请填写密码！';
				document.getElementById("message").className = "transition";
				return false;
			}else{
				/*验证用户名格式是否正确（密码不能少于8位，需至少包含字母，数字，符号中的两种。）*/
				document.getElementById("message").className = "none transition";
				owner.loginFun(loginInfo, callback);
			}
		};

		owner.loginFun = function(loginInfo, callback) {
			localStorage.clear();			
			var url = baseUrl + 'applogin/login.do?'+new Date().getTime() ;
			ajaxFun.loginpost(url, loginInfo, '', function(data, params) {
				return owner.createUser(data, callback);
			}, function(data) {
				document.getElementById("message").innerHTML = data.msg;
				document.getElementById("message").className = "transition";
				return false;
			})
		};
		/**
		 * 获取当前状态
		 **/
		owner.getUser = function() {
			var userText = localStorage.getItem('$users') || "{}";
			return JSON.parse(userText);
		};

		/**
		 * 设置当前状态
		 **/
		owner.setUser = function(user) {
			user = user || {};
			try{
				localStorage.setItem('$users', JSON.stringify(user));
			}catch(err){
				localStorage.clear();
				localStorage.setItem('$users', JSON.stringify(user));
			}
		};
		owner.createUser = function(accountInfo, callback) {
			accountInfo = accountInfo.data;
			var user = new Object();
			user.userName = accountInfo.userName;
			user.nickname = accountInfo.name;
			user.mobile = accountInfo.mobile;
			user.authenId = accountInfo.authenId;
			user.deviceId = owner.deviceId;
			user.loginID = accountInfo.id;
			owner.setUser(user);
			return callback();
		}
		
		owner.createDb=function(){
		 var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
         var msg;
         db.transaction(function (tx) {
            tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
            tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
            tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
            msg = '<p>Log message created and row inserted.</p>';
            document.querySelector('#status').innerHTML =  msg;
         });

         db.transaction(function (tx) {
            tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
               var len = results.rows.length, i;
               msg = "<p>Found rows: " + len + "</p>";
               document.querySelector('#status').innerHTML +=  msg;
					
               for (i = 0; i < len; i++){
                  msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
                  document.querySelector('#status').innerHTML +=  msg;
               }
            }, null);
         });
         
		}

		/**
		 * 新用户注册
		 **/
		owner.reg = function(regInfo, callback) {
			callback = callback || $.noop;
			regInfo = regInfo || {};
			regInfo.account = regInfo.account || '';
			regInfo.password = regInfo.password || '';
			if(regInfo.account.length < 5) {
				return callback('用户名最短需要 5 个字符');
			}
			if(regInfo.password.length < 6) {
				return callback('密码最短需要 6 个字符');
			}
			if(!checkEmail(regInfo.email)) {
				return callback('邮箱地址不合法');
			}
			var users = JSON.parse(localStorage.getItem('$users') || '[]');
			users.push(regInfo);
			localStorage.setItem('$users', JSON.stringify(users));
			return callback();
		};
		/*退出登录*/
		owner.logout = function() {
			
			// 获取所有Webview窗口
			var curr = plus.webview.currentWebview();
			var wvs = plus.webview.all();
				for (var i = 0, len = wvs.length; i < len; i++) {
					//关闭除setting页面外的其他页面
					if (wvs[i].getURL() == curr.getURL()){
						continue;
					}
					plus.webview.close(wvs[i]);
				}
					//打开login页面后再关闭setting页面
					var logurl = baseUrl + 'applogin/loginOut.do';
					var uinfo = owner.getUser();
					ajaxFun.postFun(logurl, {
						userName: uinfo.userName
					}, '', function() {
						localStorage.clear();
						plus.webview.open('../../login.html','login','','slide-in-right');
					})	 
			}
			/*获取修改密码和修改手机号的验证码*/
		owner.sendVcode = function(msgtype) {
				owner.sendMsgButton = owner.sendMsgButton ? owner.sendMsgButton : document.getElementById("sendMsg");
				owner.msgType = msgtype;
				/*发送验证码*/
				owner.sendMsgButton.addEventListener('tap', owner.sendMsg);
			}
			/*发送验证码*/
		owner.sendMsg = function() {
			var userInfo = owner.getUser();
			owner.sendMsgMobile=userInfo.mobile;
			/*如果是修改电话号码获取新号码的短信验证码就要获取电话号码的值*/
			if(owner.msgType == '03' || owner.msgType == '04') {
				var mobilev= document.getElementById("mobile").value;
				owner.sendMsgMobile =owner.strim(mobilev);
			}
		 
			/*这里是忘记密码获取验证码*/
			if(owner.msgType == '04') {
				userInfo.userName = document.getElementById("userName").value;
			}
			owner.sendMsgUrl = owner.sendMsgUrl ? owner.sendMsgUrl : baseUrl + 'traderInfoController/sendCode.do';
			if(!owner.sendMsgMobile) {
				return plus.nativeUI.alert('手机号不能为空！');
			}
			if(!userInfo.userName) {
				return plus.nativeUI.alert('账号不能为空！');
			}
			if(!owner.checkTel(owner.sendMsgMobile)) {
				return plus.nativeUI.alert('手机号不正确！');
			}

			owner.sendMsgButton.removeEventListener('tap', owner.sendMsg);
			var data = {
				mobile: owner.sendMsgMobile,
				type: owner.msgType,
				userName: userInfo.userName
			}
			ajaxFun.postFun(owner.sendMsgUrl, data, '', function() {
				owner.countdown();
			}, function(d) {
				owner.sendMsgButton.addEventListener('tap', owner.sendMsg);
				plus.nativeUI.alert(d.msg);
			})
		}
		owner.countdown = function() {
			var i =120;
			document.getElementById("sendMsg").innerHTML = i + 's';
			var count = setInterval(function() {
				if(i <= 1) {
					clearInterval(count);
					document.getElementById("sendMsg").innerHTML = '获取验证码';
					owner.sendMsgButton.addEventListener('tap', owner.sendMsg);
				} else {
					i--;
					document.getElementById("sendMsg").innerHTML = i + 's';
				}
			}, 1000);
		}
		owner.checkTel = function(tel) {
			tel = tel || '';
			var reg = /^1[3|4|5|6|7|8|9]\d{9}$/;
			return(reg.test(tel));
		};

		/**
		 * 获取验证码
		 **/
		owner.getVcode = function(mobile, callback) {
			callback = callback || $.noop;
			if(!owner.checkTel(mobile)) {
				return callback('电话号码不正确');
			}
			return true;
		};
		/**
		 * 去除左右两端空格
		 **/
		owner.strim = function(value) {
				return value.replace(/(^\s*)|(\s*$)/g, '');
			}
			/**
			 * 忘记密码
			 **/
		owner.forgetPassword = function(obj, callback) {
			if(!obj.userName || !obj.mobile || !obj.verificationCode || !obj.password || !obj.cpass) {
				plus.nativeUI.alert('请填写所有选项！'); 
				return false;
			}
			if(testStr(obj.userName)){
				plus.nativeUI.alert('用户名不能包含非法字符！'); 
				return false;
			}
			if(obj.password != obj.cpass) {
				plus.nativeUI.alert('两次输入密码不一致！'); 
				return false;
			}
			if(!owner.checkTel(obj.mobile)) {
				plus.nativeUI.alert('电话号码不正确！'); 
				return false;
			}
			
			var passResult=regPassword(obj.password);
			if(passResult.status=='error'){
				plus.nativeUI.alert('密码为至少包含字母，数字，符号中两种的8到32个字！且首字母不能为符号'); 
				return false;
			}	
			var wvs = plus.webview.all();
			var curr = plus.webview.currentWebview();
			for (var i = 0, len = wvs.length; i < len; i++) {
					//关闭除setting页面外的其他页面
					if (wvs[i].getURL() == curr.getURL()){ continue; }
					plus.webview.close(wvs[i]);
			}
	
			ajaxFun.postFun(baseUrl + 'traderInfoController/forgetPassword.do', obj, '', function() {
				localStorage.clear();
				plus.webview.open('./login.html','login','','slide-in-right');
			})
		};

		/**
		 * 获取应用本地配置
		 **/
		owner.setSettings = function(settings) {
			settings = settings || {};
			localStorage.setItem('$settings', JSON.stringify(settings));
		}

		/**
		 * 设置应用本地配置
		 **/
		owner.getSettings = function() {
				var settingsText = localStorage.getItem('$settings') || "{}";
				return JSON.parse(settingsText);
			}
			/**
			 * 获取本地是否安装客户端
			 **/
		owner.isInstalled = function(id) {
			if(id === 'qihoo' && mui.os.plus) {
				return true;
			}
			if(mui.os.android) {
				var main = plus.android.runtimeMainActivity();
				var packageManager = main.getPackageManager();
				var PackageManager = plus.android.importClass(packageManager)
				var packageName = {
					"qq": "com.tencent.mobileqq",
					"weixin": "com.tencent.mm",
					"sinaweibo": "com.sina.weibo"
				}
				try {
					return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
				} catch(e) {}
			} else {
				switch(id) {
					case "qq":
						var TencentOAuth = plus.ios.import("TencentOAuth");
						return TencentOAuth.iphoneQQInstalled();
					case "weixin":
						var WXApi = plus.ios.import("WXApi");
						return WXApi.isWXAppInstalled()
					case "sinaweibo":
						var SinaAPI = plus.ios.import("WeiboSDK");
						return SinaAPI.isWeiboAppInstalled()
					default:
						break;
				}
			}
		}
	})
}(mui, window.app = {}));